<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="产品名称" min-width="150">
        <template #default="{ row,$index }">
          <el-form-item :prop="`${$index}.productName`"  class="mb-0px!">
            <el-select  :disabled="row.disable" v-model="row.productName" @change="onChange(row.productName,$index)" placeholder="请选择名称">
                <el-option
                  v-for="dict in formData2"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
            </el-select>
          </el-form-item>
          
        </template>
      </el-table-column>
      <el-table-column label="产品单位" min-width="150">
        <template #default="{ row }">
         
          {{row.productUnitName}}
        </template>
      </el-table-column>
      <el-table-column label="产品规格" min-width="150">
        <template #default="{ row }">
          <!-- <el-form-item :prop="`${$index}.productStandards`"  class="mb-0px!">
            <el-input v-model="row.productStandards" placeholder="请输入产品规格" :readonly="true"/>
          </el-form-item> -->
          {{row.productStandards}}
        </template>
      </el-table-column>
      <el-table-column label="产品单价" min-width="150">
        <template #default="{ row }">
          <!-- <el-form-item :prop="`${$index}.productPrice`"  class="mb-0px!">
            <el-input v-model="row.productPrice" placeholder="请输入产品单价" :readonly="true"/>
          </el-form-item> -->
          {{row.productPrice}}
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input v-model="row.count" type="number" placeholder="请输入数量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="批次" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.batch`" :rules="formRules.batch" class="mb-0px!">
            <el-input v-model="row.batch" placeholder="请输入批次" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="有效期" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.validityDate`" :rules="formRules.validityDate" class="mb-0px!">
            <!-- <el-input v-model="row.count" placeholder="请输入有效期" /> -->
            <el-date-picker
              v-model="row.validityDate"
              type="date"
              :disabled-date="disabledDate"
              value-format="x"
              placeholder="选择有效时间"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="总价" min-width="150" >
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" :rules="formRules.totalPrice" class="mb-0px!">
            <el-input v-model="row.totalPrice" placeholder="请输入总价" :readonly="true"/>
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" min-width="150" >
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`"  class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ row,$index }">
          <el-button @click="handleDelete(row,$index)" link> 
          <el-icon><Delete /></el-icon></el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加单项</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { PurPurchaseOrderApi } from '@/api/erp/purpurchaseorder'
import { SupplierSendOrderApi } from '@/api/erp/suppliersendorder'
import { Delete } from '@element-plus/icons-vue' // 引入 Delete 图标

const props = defineProps<{
  purchaseOrderId: undefined,  // 采购单编号-提交供应商采购单编号（主表的关联字段）
  type:undefined, //
  zdbh:undefined, //
}>()
const disabledDate = (time) => {
  // 获取当前日期
  const today = new Date();
  // 设置时间为午夜12点
  today.setHours(0, 0, 0, 0);
  // 比较传入的日期是否小于或等于今天
  return time.getTime() < today.getTime();
};
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref([])

const formData1 = ref([])
const formData2 = ref([])
const formData3 = ref([])
const formRules = reactive({
  purchaseOrderId: [{ required: true, message: '采购单编号-提交供应商采购单编号不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
  productUnit: [{ required: true, message: '产品单位不能为空', trigger: 'change' }],
  productStandards: [{ required: true, message: '产品规格不能为空', trigger: 'blur' }],
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  // count: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  count: [
    { required: true, message: '数量不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== undefined && value !== null && Number(value) < 0) {
          callback(new Error('数量不能为负数'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  totalPrice: [{ required: true, message: '总价不能为空', trigger: 'blur' }],
  batch: [{ required: true, message: '批次不能为空', trigger: 'blur' }],
  validityDate: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.purchaseOrderId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    formData1.value = []
    formData2.value = []
    formData3.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      // console.log(props)
      // 查询订单项表
      formData1.value = await PurPurchaseOrderApi.getPurPurchaseOrderItemListByPurchaseOrderId(val)
      if(formData1.value !== null){
        formData3.value =  await SupplierSendOrderApi.getSupplierSendOrderItemPrintListByPurchaseOrderId(val)
        if(formData3.value !== null){
          formType.value = '修改'
        }else{
          formType.value = '新增'
        }
        for(let i = 0; i < formData1.value.length; i++){
          const dict ={
            value: undefined,
            label:undefined,
          }
          dict.label = formData1.value[i].productName
          dict.value = formData1.value[i].productId
          formData2.value.push(dict)
         }
         if(formData3.value !== null){
          for(let i = 0; i < formData3.value.length; i++){
          const SupplierSendOrderVO = {
            id:undefined,
            outOrderId:undefined,
            productId:undefined,
            productName:undefined,
            productUnitId:undefined,
            productUnitName:undefined,
            productStandards:undefined,
            productPrice:undefined,
            batch:undefined,
            validityDate:undefined,
            count:undefined,
            totalPrice:undefined,
            remark:undefined,
            disable:true
          }
          SupplierSendOrderVO.id = formData3.value[i].id
          SupplierSendOrderVO.outOrderId = formData3.value[i].outOrderId
          SupplierSendOrderVO.productId = formData3.value[i].productId
          SupplierSendOrderVO.productName = formData3.value[i].productName
          SupplierSendOrderVO.productUnitId = formData3.value[i].productUnitId
          SupplierSendOrderVO.productUnitName = formData3.value[i].productUnitName
          SupplierSendOrderVO.productStandards = formData3.value[i].productStandards
          SupplierSendOrderVO.productPrice = formData3.value[i].productPrice
          SupplierSendOrderVO.count = formData3.value[i].count
          SupplierSendOrderVO.validityDate = formData3.value[i].validityDate
          SupplierSendOrderVO.batch = formData3.value[i].batch
          SupplierSendOrderVO.remark = formData3.value[i].remark

          formData.value.push(SupplierSendOrderVO)
         }
         }
      }
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

const onChange = (name,index)=>{
  formData1.value.forEach(element => {
    if(name === element.productId) {
      const row = {
        productId:element.productId,
        productName:element.productName,
        productUnitName:element.productUnitName,
        productUnitId:element.productUnitId,
        productStandards:element.productStandards,
        productPrice:element.productPrice,
      }
      if (index >= 0 && index < formData.value.length) {
        formData.value.splice(index, 1, row);
      }
    }
  });
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    purchaseOrderId: undefined,
    productId: undefined,
    productUnitId: undefined,
    productUnitName: undefined,
    productStandards: undefined,
    productPrice: undefined,
    count: undefined,
    totalPrice: undefined,
    remark: undefined,
    disable :false
  }
  row.purchaseOrderId = props.purchaseOrderId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = async (row, index) => {
  try {
    // 先调用接口删除后端数据
    const res = await SupplierSendOrderApi.deleteSupplierSendOrderItem(row.id);
    if (res) {
      // 删除成功后再更新前端数据
      formData.value.splice(index, 1);
      // 可选：弹出提示信息，例如 ElMessage.success('删除成功')
    } else {
      throw new Error('删除失败');
    }
  } catch (error) {
    console.error('删除子表数据失败:', error);
    // 可选：提示用户删除失败，例如 ElMessage.error('删除失败')
  }
};

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData, formType})
</script>